package com.dorm.cj.atomicReference;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class UserAtomicReference extends AtomicReference<User> {

    public static void main2(String[] args) throws InterruptedException {
        Executor executor = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        countDownLatch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("count= " + ++User.count);
                }
            });
            countDownLatch.countDown();
        }

        TimeUnit.SECONDS.sleep(1L);
        System.out.println("最终结果：" + User.count);
    }

    public static void main(String[] args) throws InterruptedException {
//        Executor executor = Executors.newFixedThreadPool(10);
//        CountDownLatch countDownLatch = new CountDownLatch(10);
//
//        UserAtomicReference userAtomicReference = new UserAtomicReference();
//        userAtomicReference.set(new User());
//        for (int i = 0; i < 10; i++) {
//            executor.execute(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        countDownLatch.await();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//
//                    User old = userAtomicReference.getAndSet(userAtomicReference.get().setCount(userAtomicReference.get().getCount() + 1));
//                    System.out.println("count= " + old.getCount());
//                }
//            });
//            countDownLatch.countDown();
//        }
//
//        TimeUnit.SECONDS.sleep(1L);
//        System.out.println("最终结果：" + userAtomicReference.get().getCount());
        User user = new User();
        UserAtomicReference userAtomicReference = new UserAtomicReference();
        userAtomicReference.set(user);
        user.setCount(11);
        System.out.println(userAtomicReference.getAndSet(user).getCount());
        user.setCount(12);
        System.out.println(userAtomicReference.get().getCount());

        System.out.println(userAtomicReference.compareAndSet(new User(),user));
    }
}
